package com.xpc.test.base;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述：
 *
 * @author xpc on 2024/4/3 14:41
 */
@Data
public class QueryObject<T> {

    private QueryOption queryOption;

    public QueryWrapper<T> buildQuery() {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        this.buildQuery(queryWrapper);
        List<SortItem> sortItems = this.queryOption.getSort();
        if (CollUtil.isNotEmpty(sortItems)) {
            sortItems = sortItems.stream().filter(item -> CharSequenceUtil.isNotEmpty(item.getField())).sorted(Comparator.comparing(SortItem::getOrder)).collect(Collectors.toList());
            for (SortItem item : sortItems) {
                if (Boolean.TRUE.equals(item.getAsc())) {
                    queryWrapper.orderByAsc(QueryObject.convert(item.getField()));
                } else {
                    queryWrapper.orderByDesc(QueryObject.convert(item.getField()));
                }
            }
        }
        return queryWrapper;
    }

    protected void buildQuery(QueryWrapper<T> queryWrapper) {
        // 继承方法
    }

    public Page<T> getPage() {
        return new Page<>(this.queryOption.getCurrent(), this.queryOption.getSize());
    }

    public static String convert(String camelCase) {
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < camelCase.length(); i++) {
            char c = camelCase.charAt(i);

            if (Character.isUpperCase(c)) { // 如果当前字符是大写字母
                result.append("_"); // 在上一个单词与当前单词之间添加下划线

                if (i > 0 && Character.isLowerCase(camelCase.charAt(i - 1))) { // 判断上一个字符是否为小写字母
                    result.append(Character.toLowerCase(c)); // 直接将当前字符转换为小写字母
                }
            } else {
                result.append(c); // 非大写字母直接添加到结果字符串中
            }
        }

        return result.toString();
    }
}
